package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //获取前端参数
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();
        //判断是否为空
        if(StringUtils.isEmpty(phone)&& StringUtils.isEmpty(password)){
            //游客登陆
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
        //正常登录逻辑
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        // 判断手机号是否存在
        wrapper.eq(ApUser::getPhone,loginDto.getPhone());
        ApUser apUser = apUserMapper.selectOne(wrapper);
        if(apUser == null){
            //用户不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        String passwordDB = apUser.getPassword();
        String salt = apUser.getSalt();
        String passwordMD5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(!passwordDB.equals(passwordMD5)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //清空敏感数据
        apUser.setSalt("");
        apUser.setPassword("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
        map.put("data",apUser);
        return ResponseResult.okResult(map);
    }
}